package a66weding.com.jiehuntong.activity.me;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.xutils.x;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.MainActivity;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CartChangeResultBean;
import a66weding.com.jiehuntong.beans.CollectionBatchBean;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MeShoppingCartBean;
import a66weding.com.jiehuntong.beans.MeShoppingCartDeleteBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.view.ConfirmLoginDialog;

import static a66weding.com.jiehuntong.R.id.tv_indent_code;

/**
 * 我的—购物车界面
 * Created by Administrator on 2016/7/7.
 */
public class MeShoppingCartActivity extends MeBaseActivity implements View.OnClickListener, OnNetResultListener {
    private LinearLayout mBackLay;
    private LinearLayout mCompileLay;
    private LinearLayout mShowShoppingCartLay;
    private LinearLayout mNoShoppingCartLay;
    private TextView mBackContentTv;
    private TextView mHeaderTitleTv;
    private TextView mRightTitleTv;
    private TextView mAccomplishTv;
    private TextView mPayTv;
    private TextView mSaveTv;
    private Button mCompileBtn;
    private Button mAccomplishBtn;
    private Button mGoShopBt;
    private MeShoppingCartBean meShoppingCartBean;
    private MeShoppingCartDeleteBean meShoppingCartDeleteBean;
    private List<MeShoppingCartBean.DataBean> list;
    private ExpandableListView mContentList;
    private MyExpandListAdapter myExpandListAdapter;
    private boolean isCompile;  //全局的编辑和完成按钮设置boolean值
    private CheckBox mAllCheck;
    private int mCurrentGroupposition;
    private int mCurrentChildposition;
    public static int startForResult = 5;
    private int i_id;
    private static final int DIALOGDISSMISS = 2;
    private int[] waitpayIds;
    private boolean isOnClickAllCheckedCar = true;
    private StringBuffer buffer_delete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_shoppingcart);
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("MeShoppingCartActivity", this);
        Intent intent = getIntent();
        if (intent != null) {
            boolean isSelectGoods = intent.getBooleanExtra("isSelectGoods", false);
            if (isSelectGoods) {
                waitpayIds = intent.getIntArrayExtra("waitpayId");
            }
        }
        boolean login = ((GlobalApplication) getApplication()).isLogin();
        if (login) {
            i_id = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
            initview();
            initData();
        }
    }

    @Override
    protected void onResume() {
        initData();
        super.onResume();
    }

    private void initData() {
        String url = UrlDealUtil.getRealUrlNewIdApi(RequestCode.GET_MEMBERSHOPS);
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST,
                url, this, MeShoppingCartBean.class, RequestCode.GET_MEMBERSHOPS);
        HttpHandleUtil.executeCommonGet(MeShoppingCartActivity.this, httpRequestBean);
    }
    //修改购物车
            private void getCartCahnge(int groupPosition, int childPosition, int quantity) {

        String oldUrl = UrlDealUtil.getRealUrlNewIdApi(RequestCode.UPDATESHOPSBYPRODUCTIDANDMEMBER);
        int goods_id = list.get(groupPosition).getCartItems().get(childPosition).getGoods_id();

        String url = oldUrl + "&productID=" + goods_id + "&number=" + quantity;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                MeShoppingCartActivity.this, CartChangeResultBean.class, RequestCode.UPDATESHOPSBYPRODUCTIDANDMEMBER);
        HttpHandleUtil.executeCommonPost(MeShoppingCartActivity.this, httpRequestBean);
    }
    private void initview() {
        mBackLay = (LinearLayout) findViewById(R.id.lay_head_backlay);
        mCompileLay = (LinearLayout) findViewById(R.id.ll_me_compile);
        mShowShoppingCartLay = (LinearLayout) findViewById(R.id.ll_me_shopping_cart_list);
        mNoShoppingCartLay = (LinearLayout) findViewById(R.id.ll_me_shopping_cart_no);
        mBackContentTv = (TextView) findViewById(R.id.headleft_title_tv);
        mHeaderTitleTv = (TextView) findViewById(R.id.headcenter_title_tv);
        mRightTitleTv = (TextView) findViewById(R.id.headright_title_tv);
        mAccomplishTv = (TextView) findViewById(R.id.tv_me_accomplish);
        mPayTv = (TextView) findViewById(R.id.tv_me_pay_money); // 付款金额
        mSaveTv = (TextView) findViewById(R.id.tv_me_save_money); // 节省金额
        mContentList = (ExpandableListView) findViewById(R.id.lv_me_indent_shopping);
        mCompileBtn = (Button) findViewById(R.id.btn_me_compile);
        mAccomplishBtn = (Button) findViewById(R.id.btn_me_accomplish);
        mAllCheck = (CheckBox) findViewById(R.id.cb_me_all);
        mGoShopBt = (Button) findViewById(R.id.btn_go_shopping);
        mBackContentTv.setText("返回");
        mHeaderTitleTv.setText("购物车");
        mRightTitleTv.setText("编辑");
        mRightTitleTv.setEnabled(false);
        mAllCheck.setEnabled(true);
        mBackLay.setOnClickListener(this);
        mRightTitleTv.setOnClickListener(this);
        mCompileBtn.setOnClickListener(this);
        mGoShopBt.setOnClickListener(this);
        mAccomplishTv.setOnClickListener(this);
        mAccomplishBtn.setOnClickListener(this);
        mAllCheck.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                Log.i("1101", "触摸购物车" );
                isOnClickAllCheckedCar = true;
                return false;
            }
        });
        mAllCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.i("1101", "onCheckedChanged: 购物车用户想" + isChecked);
                if (isOnClickAllCheckedCar) {//如果是点击的全选购物车的按钮才有效.
                    Log.i("1101", "onCheckedChanged: 是点击的购物车全选");
                    for (MeShoppingCartBean.DataBean md : list) {
                        md.setGroupChecked(isChecked);
                        for (MeShoppingCartBean.DataBean.CartItemsBean mdc : md.getCartItems()) {
                            mdc.setChildChecked(isChecked);
                        }
                    }
                    refreshListView();
                }
            }
        });
    }
    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.lay_head_backlay: //点击我的，返回到上一级界面
                intent.setClass(MeShoppingCartActivity.this, MainActivity.class);
                intent.putExtra("isChange", false);
                finish();
                break;
            case R.id.headright_title_tv: //点击编辑之后的事件
                //添加判断 如果在没有数据的时候
                if (mNoShoppingCartLay.getVisibility() == View.GONE) {
                    if (mRightTitleTv.getText().equals("编辑")) {
                        mRightTitleTv.setText("完成");
                        mCompileLay.setVisibility(View.GONE);
                        mAccomplishTv.setVisibility(View.VISIBLE);
                        mCompileBtn.setVisibility(View.GONE);
                        mAccomplishBtn.setVisibility(View.VISIBLE);
                        isCompile = true;
                        if (list.size() != 0) {
                            for (int i = 0; i < list.size(); i++) {
                                list.get(i).setEdit(true);
                            }
                            refreshListView();
                        }
                    } else {    //点击完成
                        mRightTitleTv.setText("编辑");
                        mCompileLay.setVisibility(View.VISIBLE);
                        mAccomplishTv.setVisibility(View.GONE);
                        mCompileBtn.setVisibility(View.VISIBLE);
                        mAccomplishBtn.setVisibility(View.GONE);
                        isCompile = false;
                        if (list.size() != 0) {
                            for (int i = 0; i < list.size(); i++) {
                                list.get(i).setEdit(false);
                            }
                            refreshListView();
                        }
                    }
                } else {
                    CUtils.showToast("无数据");
                }
                break;
            case R.id.btn_me_compile: //点击结算按钮,跳转到结算界面
                if (mPayTv.getText().equals("0.0")) {
                    Toast.makeText(MeShoppingCartActivity.this, "请您选择要结算的商品", Toast.LENGTH_SHORT).show();
                } else {
                    // 打开结算界面的时候把javabean传递过去
               /*  int selectCount = 0;
                     List<MeShoppingCartBean.DataBean> data = meShoppingCartBean.getData();
                  for (int i = 0; i < data.size(); i++) {
                        List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = data.get(i).getCartItems();
                        for (int j = 0; j < cartItems.size(); j++) {
                            if (cartItems.get(j).isChildChecked()) {
                                selectCount++;
                            }
                        }
                    }*/
                    intent.setClass(this, MeCompileActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("cartBean", meShoppingCartBean);
                    intent.putExtra("cartBd", bundle);
                    startActivityForResult(intent, startForResult);
                }
                break;
            case R.id.tv_me_item_compile: //group编辑
                int groupposition = (int) v.getTag();
                boolean groupedit = list.get(groupposition).isEdit();
                if (groupedit) {
                    list.get(groupposition).setEdit(false);
                } else {
                    list.get(groupposition).setEdit(true);
                }
                refreshListView();

                break;
            case R.id.tv_money_add: //加一件商品
                mCurrentGroupposition = (int) v.getTag(R.id.tag_first);
                mCurrentChildposition = (int) v.getTag(R.id.tag_second);

                int quantity = list.get(mCurrentGroupposition).getCartItems().get(mCurrentChildposition).getQuantity();
                quantity++;
                getCartCahnge(mCurrentGroupposition, mCurrentChildposition, quantity);

                break;
            case R.id.tv_indent_money_minus: //减一件商品
                mCurrentGroupposition = (int) v.getTag(R.id.tag_first);
                mCurrentChildposition = (int) v.getTag(R.id.tag_second);

                int quantity2 = list.get(mCurrentGroupposition).getCartItems().get(mCurrentChildposition).getQuantity();
                quantity2--;
                getCartCahnge(mCurrentGroupposition, mCurrentChildposition, quantity2);

                break;
            case R.id.btn_go_shopping: // 去逛逛

                intent.setClass(MeShoppingCartActivity.this, MainActivity.class);
                intent.putExtra("index", 1);
                intent.putExtra("isChange", true);
                MainActivity mainActivity = (MainActivity) ((GlobalApplication) getApplication()).getMainActivityManager().getActivity("MainActivity");
                if (mainActivity != null) {
                    mainActivity.isQuGuangguang = true;
                }
                setResult(MainActivity.getResultForCartCode, intent);
                startActivity(intent);
                finish();

                break;
            case R.id.tv_me_accomplish: //移到收藏夹
                Tools.showWaitDialogSmall(this, "请稍后...", true);
                ArrayList<CollectionBatchBean> collectList = new ArrayList<CollectionBatchBean>();
                CollectionBatchBean collectBean = null;
                if (list != null) {
                    for (int i = 0; i < list.size(); i++) {
                        List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = list.get(i).getCartItems();
                        for (int j = 0; j < cartItems.size(); j++) {
                            MeShoppingCartBean.DataBean.CartItemsBean cartItemsBean = cartItems.get(j);
                            if (cartItems.get(j).isChildChecked()) {
                                collectBean = new CollectionBatchBean();
                                collectBean.setI_MemberID(i_id);
                                collectBean.setBusinessID(cartItems.get(j).getBusiness_id());
                                collectBean.setProductID(cartItems.get(j).getGoods_id());
                                collectList.add(collectBean);
                            }
                        }
                    }
                    String json = new Gson().toJson(collectList);
                    String url = RequestCode.post_CollectionCreateList;
                    url += "&collsStr=" + json;
                    HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                            MeShoppingCartActivity.this, CommonResultBean.class, RequestCode.post_CollectionCreateList);
                    HttpHandleUtil.executeCommonPost(MeShoppingCartActivity.this, httpRequestBean);
                }
                break;
            case R.id.btn_me_accomplish: //删除全部商品
                buffer_delete = new StringBuffer();
                if (list != null) {
                    for (int i = 0; i < list.size(); i++) {
                        List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = list.get(i).getCartItems();
                        for (int j = 0; j < cartItems.size(); j++) {
                            MeShoppingCartBean.DataBean.CartItemsBean cartItemsBean = cartItems.get(j);
                            if (cartItems.get(j).isChildChecked()) {
                                String id = String.valueOf(cartItems.get(j).getGoods_id());
                                buffer_delete.append(id + ",");
                            }
                        }
                    }
                }
                if (buffer_delete !=null&& buffer_delete.toString().length()>0&& buffer_delete.toString().endsWith(",")){
                final ConfirmLoginDialog confirmDialog = new ConfirmLoginDialog(this, "是否删除已选中商品？", "是", "否", R.layout.pop_tologin);
                confirmDialog.show();
                confirmDialog.setClicklistener(new ConfirmLoginDialog.ClickListenerInterface() {
                    @Override
                    public void doConfirm() {
                        Tools.showWaitDialog(MeShoppingCartActivity.this, "请稍后...");
                            String str = buffer_delete.toString();
                            String ids = str.substring(0, str.length() - 1);
                            String oldUrl = UrlDealUtil.getRealUrlNewIdApi(RequestCode.DELSHOPSBYPRODUCTIDANDMEMBER);
                            String url = oldUrl + "&productID=" + ids;
                            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                            MeShoppingCartActivity.this, MeShoppingCartDeleteBean.class, RequestCode.DELSHOPSBYPRODUCTIDANDMEMBER);
                            HttpHandleUtil.executeCommonPost(MeShoppingCartActivity.this, httpRequestBean);
                        confirmDialog.dismiss();
                        }

                    @Override
                    public void doCancel() {
                        confirmDialog.dismiss();
                    }
                });
                }else {
                    CUtils.showToastInCenter("未选择商品！");
                }
                break;
        }
    }
    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        mAllCheck.setEnabled(true);
        mRightTitleTv.setEnabled(true);
        Tools.dismissWaitDialog();
        if (data instanceof CommonResultBean) {
            CommonResultBean commonData = (CommonResultBean) data;
            switch (commonData.getResCode()) {
                case "0000":
                    Tools.showResultDialogSmall(this, "收藏成功", true);
                    mHandler.sendEmptyMessageDelayed(DIALOGDISSMISS, 1000);
                    break;
                case "0003":

                case "0005":
                    Tools.showResultDialogSmall(this, "该商品已收藏", true);
                    mHandler.sendEmptyMessageDelayed(DIALOGDISSMISS, 2000);
                    break;
                default:
                    Tools.showResultDialogSmall(this, "该商品已收藏", true);
                    mHandler.sendEmptyMessageDelayed(DIALOGDISSMISS, 1000);
            }
        } else if (data instanceof MeShoppingCartBean) {
            meShoppingCartBean = (MeShoppingCartBean) data;
            list = meShoppingCartBean.getData();
            if (list == null) {
                mShowShoppingCartLay.setVisibility(View.GONE);
                mNoShoppingCartLay.setVisibility(View.VISIBLE);
            } else {
                mShowShoppingCartLay.setVisibility(View.VISIBLE);
                mNoShoppingCartLay.setVisibility(View.GONE);
                setSelectGoods(list);
                myExpandListAdapter = new MyExpandListAdapter();
                mContentList.setAdapter(myExpandListAdapter);
                mContentList.setGroupIndicator(null);
                for (int i = 0; i < list.size(); i++) {
                    mContentList.expandGroup(i);
                }
                refreshMoney();
            }
        }

        // 如果删除成功,则再加载一次界面
        else if (data instanceof MeShoppingCartDeleteBean) {
            meShoppingCartDeleteBean = (MeShoppingCartDeleteBean) data;
            switch (meShoppingCartDeleteBean.getResCode()) {
                case "0000":
                    mAllCheck.setChecked(false);//因为要重新请求新的购物车了，所以购物车中商品选中状态会重置为不选中，所以这里整个购物车的选中要更新下
                    initData();
                    Toast.makeText(MeShoppingCartActivity.this, "删除商品成功", Toast.LENGTH_SHORT).show();
                    Intent intent2 = new Intent();
                    intent2.setAction("a66weding.com.jiehuntong.pager.CATEGURYPAGER");
                    //发送无序广播
                    sendBroadcast(intent2);
                    break;
                case "0005":
                    break;
            }

        } else if (data instanceof CartChangeResultBean) {
            CartChangeResultBean cartChange = (CartChangeResultBean) data;
            switch (cartChange.getResCode()) {
                case "0000":


                    Intent intent2 = new Intent();
                    intent2.setAction("a66weding.com.jiehuntong.pager.CATEGURYPAGER");
                    //发送无序广播
                    sendBroadcast(intent2);

                    int goods_id = cartChange.getResult().getGoods_id();
                    int quantity = cartChange.getResult().getQuantity();
                    for (int i = 0; i < list.size(); i++) {
                        List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = list.get(i).getCartItems();
                        for (int j = 0; j < cartItems.size(); j++) {
                            if (goods_id == cartItems.get(j).getGoods_id()) {
                                cartItems.get(j).setQuantity(quantity);
                                break;
                            }
                        }
                    }
                    refreshListView();
                    break;
                case "0001":

                    break;
            }

        }


    }
    @Override
    public void onError(ErrorBean errorBean) {
        Tools.dismissWaitDialog();
        switch (errorBean.getErrorCode()) {
            case ErrorBean.NONET:
            case ErrorBean.TIMEOUT:
                mAllCheck.setEnabled(false);
                mRightTitleTv.setEnabled(false);

                break;
        }

    }
    public class MyExpandListAdapter extends BaseExpandableListAdapter {
        @Override
        public int getGroupCount() {
            return list.size();
        }
        @Override
        public int getChildrenCount(int groupPosition) {
            List<MeShoppingCartBean.DataBean.CartItemsBean> mscData = list.get(groupPosition).getCartItems();
            return mscData.size();
        }
        @Override
        public Object getGroup(int groupPosition) {
            return list.get(groupPosition);
        }
        @Override
        public Object getChild(int groupPosition, int childPosition) {
            MeShoppingCartBean.DataBean.CartItemsBean cartItemsBean = list.get(groupPosition).getCartItems().get(childPosition);
            return cartItemsBean;
        }
        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }
        @Override
        public long getChildId(int groupPosition, int childPosition) {
            List<MeShoppingCartBean.DataBean.CartItemsBean> mscData = list.get(groupPosition).getCartItems();
            return childPosition;
        }
        @Override
        public boolean hasStableIds() {
            return false;
        }
        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            MeShoppingCartBean.DataBean dataBean = list.get(groupPosition);
            GroupHolder mHolder;
            convertView = View.inflate(getApplicationContext(), R.layout.item_me_indent_shoppingcat_father, null);
            mHolder = new GroupHolder();
            mHolder.mShopingNameTv = (TextView) convertView.findViewById(R.id.tv_me_shopping_cart_title);
            mHolder.mCompile = (TextView) convertView.findViewById(R.id.tv_me_item_compile);
            mHolder.mTitleCheck = (CheckBox) convertView.findViewById(R.id.cb_me_title);
            mHolder.mShopingNameTv.setText(dataBean.getBusinessName());
            boolean groupChecked = dataBean.isGroupChecked();
            mHolder.mTitleCheck.setChecked(groupChecked);
            mHolder.mTitleCheck.setTag(groupPosition);
            mHolder.mTitleCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    Log.i("1101", "onCheckedChanged: 店铺全选");
                    int groupposition = (int) buttonView.getTag();
                    MeShoppingCartBean.DataBean dataBean1 = list.get(groupposition);
                    dataBean1.setGroupChecked(isChecked);
                    List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems1 = dataBean1.getCartItems();
                    for (int i = 0; i < cartItems1.size(); i++) {
                        cartItems1.get(i).setChildChecked(isChecked);
                    }
                    //更改整个购物车的全选按钮状态
                    boolean isAllChecked = true;
                    for (MeShoppingCartBean.DataBean mp : list) {
                        if (!mp.isGroupChecked()) {//如果有一家的商品不是全选那么整个购物车就不是全选
                            isAllChecked = false;
                            break;
                        }
                    }
                    //标记是否点击的是购物车全选，这里是点击的店铺全选，所以这里是false
                    isOnClickAllCheckedCar = false;
                    mAllCheck.setChecked(isAllChecked);
                    refreshListView();
                }
            });

            boolean isedit = dataBean.isEdit();
            if (isedit) {
                mHolder.mCompile.setText("完成");
            } else {
                mHolder.mCompile.setText("编辑");
            }
            mHolder.mCompile.setTag(groupPosition);
            mHolder.mCompile.setOnClickListener(MeShoppingCartActivity.this);
            if (isCompile) {
                mHolder.mCompile.setVisibility(View.GONE);
            } else {
                mHolder.mCompile.setVisibility(View.VISIBLE);
            }
            return convertView;
        }
        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            final MeShoppingCartBean.DataBean dataBean = list.get(groupPosition);
            List<MeShoppingCartBean.DataBean.CartItemsBean> mscData = dataBean.getCartItems();
            final MeShoppingCartBean.DataBean.CartItemsBean cartItemsBean = mscData.get(childPosition);
            final ItemHolder mHolder;
            convertView = View.inflate(getApplicationContext(), R.layout.item_me_indent_shoppingcat, null);
            mHolder = new ItemHolder();
            mHolder.mShowMoney = (LinearLayout) convertView.findViewById(R.id.ll_show_money);
            mHolder.mSetMoney = (LinearLayout) convertView.findViewById(R.id.ll_set_money);
            mHolder.mIndentIv = (ImageView) convertView.findViewById(R.id.img_indent);
            mHolder.mItemCheck = (CheckBox) convertView.findViewById(R.id.cb_me_item);
            x.image().bind(mHolder.mIndentIv, cartItemsBean.getImg_url());
            boolean isedit = dataBean.isEdit();
            if (isedit) {
                mHolder.mShowMoney.setVisibility(View.GONE);
                mHolder.mSetMoney.setVisibility(View.VISIBLE);
                TextView setTitleTv = (TextView) mHolder.mSetMoney.findViewById(R.id.tv_indent_code_1);
                setTitleTv.setText(cartItemsBean.getTitle());
                TextView setMoneyTv = (TextView) mHolder.mSetMoney.findViewById(R.id.tv_money_1);
                TextView setOldMoneyTv = (TextView) mHolder.mSetMoney.findViewById(R.id.tv_old_money1);
                TextView setStandTv = (TextView) mHolder.mSetMoney.findViewById(R.id.tv_me_standard_1);
                mHolder.mDeleteIv = (ImageView) convertView.findViewById(R.id.iv_delete_address);
                mHolder.mAddTv = (TextView) convertView.findViewById(R.id.tv_money_add);
                mHolder.mMinusTv = (TextView) convertView.findViewById(R.id.tv_indent_money_minus);
                mHolder.mQuantityTv = (TextView) convertView.findViewById(R.id.tv_me_quantity);
                if (cartItemsBean.getSpec_text().equals("")) {
                    setStandTv.setText("规格:——");
                } else {
                    setStandTv.setText("规格:" + cartItemsBean.getSpec_text());
                }
                // 显示商品价格和销售价格
                double user_price = cartItemsBean.getUser_price();
                double sell_price = cartItemsBean.getSell_price();
                setMoneyTv.setText(String.valueOf(user_price));
                setOldMoneyTv.setText(String.valueOf(sell_price));
                if (user_price == sell_price) {
                    setOldMoneyTv.getPaint().setFlags(0);
                } else {
                    setOldMoneyTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //设置中划线
                }
                // 点击加号增加数量
                mHolder.mAddTv.setTag(R.id.tag_first, groupPosition);
                mHolder.mAddTv.setTag(R.id.tag_second, childPosition);
                mHolder.mAddTv.setOnClickListener(MeShoppingCartActivity.this);
                mHolder.mQuantityTv.setText(String.valueOf(cartItemsBean.getQuantity()));
                // 点击减号减去数量
                mHolder.mMinusTv.setTag(R.id.tag_first, groupPosition);
                mHolder.mMinusTv.setTag(R.id.tag_second, childPosition);
                mHolder.mMinusTv.setOnClickListener(MeShoppingCartActivity.this);
                // 移出购物车
                mHolder.mDeleteIv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showLoginDialog(MeShoppingCartActivity.this, "是否确定删除?", "确定", "取消", cartItemsBean);
                    }
                });

            } else {
                mHolder.mSetMoney.setVisibility(View.GONE);
                mHolder.mShowMoney.setVisibility(View.VISIBLE);
                TextView titleTv = (TextView) mHolder.mShowMoney.findViewById(tv_indent_code);
                Log.i("购物", "getChildView: "+cartItemsBean.getTitle());
                titleTv.setText(cartItemsBean.getTitle());

                TextView setMoneyTv = (TextView) mHolder.mShowMoney.findViewById(R.id.tv_money);
                TextView setOldMoey = (TextView) convertView.findViewById(R.id.tv_me_old_money);
                TextView standardTv = (TextView) mHolder.mShowMoney.findViewById(R.id.tv_me_standard);
                mHolder.mNumberTv = (TextView) convertView.findViewById(R.id.tv_me_number);
                // 设置数量
                mHolder.mNumberTv.setText("×" + cartItemsBean.getQuantity());
                if (cartItemsBean.getSpec_text().equals("")) {
                    standardTv.setText("规格:——");
                } else {
                    standardTv.setText("规格:" + cartItemsBean.getSpec_text());
                }
                // 显示商品价格和销售价格
                double user_price = cartItemsBean.getUser_price();
                double sell_price = cartItemsBean.getSell_price();
                Log.i("购物", "getChildView: "+String.valueOf(user_price).length());

                if (String.valueOf(user_price).length()>=6){//千元
                    setMoneyTv.setTextSize(13);
                    setOldMoey.setTextSize(13);
                    mHolder.mNumberTv.setTextSize(13);
                }
                if (String.valueOf(user_price).length()>7){//几十万元
                    TextView  tv_indent_money=  (TextView) findViewById(R.id.tv_indent_money);
                    setMoneyTv.setTextSize(12);
                    setOldMoey.setTextSize(11);
                    tv_indent_money.setTextSize(12);
                    mHolder.mNumberTv.setTextSize(13);
                }

                setMoneyTv.setText(String.valueOf(user_price));
                setOldMoey.setText(String.valueOf(sell_price));
                setOldMoey.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //设置中划线
            }
            boolean groupChecked = dataBean.isGroupChecked();
            boolean childChecked1 = cartItemsBean.isChildChecked();
            if (groupChecked) {
                mHolder.mItemCheck.setChecked(groupChecked);
            } else {
                mHolder.mItemCheck.setChecked(childChecked1);
            }
            mHolder.mItemCheck.setTag(R.id.tag_first, groupPosition);
            mHolder.mItemCheck.setTag(R.id.tag_second, childPosition);
            mHolder.mItemCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    Log.i("1101", "onCheckedChanged: 一件物品");
                    int gropIndex = (int) buttonView.getTag(R.id.tag_first);
                    int childIndex = (int) buttonView.getTag(R.id.tag_second);
                    //改变当前选择的商品是否选中的标志
                    for (int i = 0; i < list.get(gropIndex).getCartItems().size(); i++) {
                        if (i == childIndex) {
                            list.get(gropIndex).getCartItems().get(i).setChildChecked(isChecked);
                            break;
                        }
                    }
                    //更新店铺全选按钮
                    boolean isStoreChecked=true;//当前店铺是否全选
                    for (MeShoppingCartBean.DataBean.CartItemsBean mbc : list.get(gropIndex).getCartItems()) {
                        if (!mbc.isChildChecked()) {//只要有一个不是选中的
                            isStoreChecked=false;
                            break;
                        }
                    }
                    list.get(gropIndex).setGroupChecked(isStoreChecked);
                    //更新购物车全选按钮
                    boolean isAllChecked = true;
                    for (MeShoppingCartBean.DataBean mp : list) {
                        for (MeShoppingCartBean.DataBean.CartItemsBean mpc : mp.getCartItems()) {
                            if (!mpc.isChildChecked()) {
                                isAllChecked = false;
                                break;
                            }
                        }
                    }
                    isOnClickAllCheckedCar = false;
                    mAllCheck.setChecked(isAllChecked);
                    //刷新页面
                    refreshListView();
                    //刷新金额
                    refreshMoney();
                }
            });

            return convertView;
        }
        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }
    // 父View的Holder
    class GroupHolder {
        TextView mShopingNameTv, mCompile;
        CheckBox mTitleCheck;
    }
    // 子View的Holder
    class ItemHolder {
        LinearLayout mShowMoney, mSetMoney;
        TextView mAddTv, mMinusTv, mQuantityTv, mMoneyTv,
                mShopingCartTitleTv, mStandardTv, mStandard1Tv,
                mShopingCartTitle1Tv, mCompileMoneyTv, mNumberTv;
        ImageView mIndentIv, mDeleteIv;
        CheckBox mItemCheck;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == startForResult) {
            if (data != null) {
                meShoppingCartBean = (MeShoppingCartBean) data.getExtras().get("cartBean");
                list = meShoppingCartBean.getData();
                myExpandListAdapter = new MyExpandListAdapter();
                mContentList.setAdapter(myExpandListAdapter);
                refreshListView();
            }
        }
    }
    private void setSelectGoods(List<MeShoppingCartBean.DataBean> list) {
        if (waitpayIds != null && list != null) {
            for (int i = 0; i < list.size(); i++) {
                int businessID = list.get(i).getBusinessID();
                if (waitpayIds[waitpayIds.length - 1] == businessID) {
                    List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = list.get(i).getCartItems();
                    for (int j = 0; j < cartItems.size(); j++) {
                        int goods_id = cartItems.get(j).getGoods_id();
                        for (int k = 0; k < waitpayIds.length - 1; k++) {
                            if (goods_id == waitpayIds[k]) {
                                cartItems.get(j).setChildChecked(true);
                            }
                        }
                    }
                }
            }
        }
    }
    private void refreshMoney() {
        double countMoney = 0;
        double shopCountMoney = 0;
        for (int i = 0; i < list.size(); i++) {
            List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = list.get(i).getCartItems();
            for (int j = 0; j < cartItems.size(); j++) {
                if (cartItems.get(j).isChildChecked()) {
                    int quantity = cartItems.get(j).getQuantity();
                    countMoney += quantity * cartItems.get(j).getUser_price();
                    shopCountMoney += quantity * cartItems.get(j).getSell_price();
                }
            }
        }
        BigDecimal bigDecimal = new BigDecimal(countMoney);
        double newcountMoney = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        bigDecimal = new BigDecimal(shopCountMoney - countMoney);
        double saveMoney = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        mPayTv.setText(String.valueOf(newcountMoney));
        mSaveTv.setText(String.valueOf(saveMoney));
    }
    private void refreshListView() {
        if (myExpandListAdapter != null) {
            myExpandListAdapter.notifyDataSetChanged();
            for (int i = 0; i < list.size(); i++) {
                mContentList.collapseGroup(i);
                mContentList.expandGroup(i);
            }
        }
        refreshMoney();
    }
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DIALOGDISSMISS:
                    Tools.dismissWaitDialog();
                    break;
            }
        }
    };
    /**
     * 是否移出购物车
     * @param context
     * @param title
     * @param confirm
     * @param cancel
     */
    public void showLoginDialog(Context context, String title, String confirm, String cancel, final MeShoppingCartBean.DataBean.CartItemsBean cartItemsBean) {
        final ConfirmLoginDialog confirmDialog = new ConfirmLoginDialog(context, title, confirm, cancel, R.layout.pop_tologin);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmLoginDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                String oldUrl = UrlDealUtil.getRealUrlNewIdApi(RequestCode.DELSHOPSBYPRODUCTIDANDMEMBER);
                String url = oldUrl + "&productID=" + cartItemsBean.getGoods_id();
                HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                        MeShoppingCartActivity.this, MeShoppingCartDeleteBean.class, RequestCode.DELSHOPSBYPRODUCTIDANDMEMBER);
                HttpHandleUtil.executeCommonPost(MeShoppingCartActivity.this, httpRequestBean);
                confirmDialog.dismiss();
            }

            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }
}
